package com.bawei.common.recyclerview

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * Author: Jason Zhang
 * Date: 2024/5/14
 * Desc: RecyclerView的Item装饰器
 */
class RecyclerItemDecoration constructor(private var top: Int = 0, private var bottom: Int = 0, private var left: Int = 0, private var right: Int = 0): RecyclerView.ItemDecoration() {

    private var dividerColor = Color.TRANSPARENT
    private var dividerHeight = 5
    private var dividerMarginHeight = 0
    private var mPaint: Paint = Paint()

    init {
        mPaint.color = dividerColor
    }

    /**
     * 声明次构造方法
     */
    constructor(top: Int, bottom: Int, left: Int, right: Int, dividerColor: Int, dividerHeight: Int, dividerMarginHeight: Int) : this(top, bottom, left, right){
        this.dividerColor = dividerColor
        this.dividerHeight = dividerHeight
        this.dividerMarginHeight = dividerMarginHeight
    }


    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        if (top == 0 && bottom == 0 && left == 0 && right == 0) return //直接返回，防止组件重新测量绘制，提升性能
        outRect.set(left, top, right, bottom)
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
    }

    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDrawOver(c, parent, state)
        var child: View
        var childTop: Int
        var childBottom: Int
        var childLeft: Int
        var childRight: Int
        for (i in 0 until parent.childCount){
            child = parent.getChildAt(i)
            //判断是否为奇数位
            var index =  (i + 1) % 2
            childTop = child.top + dividerMarginHeight
            childLeft =  if (index > 0) child.left else child.left - left
            childRight = if (index > 0) child.right - right else child.right
            childBottom = child.bottom + dividerHeight
            //绘制分割线
            c.drawRect(childLeft.toFloat(), childTop.toFloat(), childRight.toFloat(), childBottom.toFloat(), mPaint)
        }
    }

}